/**
 * Copyright (c) 2010 S9,Inc.All rights reserved.
 * Created by 2012-6-1 
 */
package cn.jdy.platform.admin;

import cn.jdy.authority.entity.User;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.JsonUtil;
import cn.jdy.framework.util.SpringUploadFile;
import cn.jdy.framework.util.StringUtil;
import cn.jdy.platform.entity.ConfType;
import cn.jdy.platform.entity.ConfValue;
import cn.jdy.platform.service.ConfService;
import cn.jdy.platform.service.ConfTypeService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项目配置部署控制类
 *
 * @author WuZhiliang
 * @description: 项目配置部署控制类。
 * @date 2013-07-15 10:10
 */
@Controller
@RequestMapping("/conf")
public class ConfCtrl {

	@Autowired
	private ConfService confService;
	@Autowired
	private ConfTypeService confTypeService;
	@Autowired
	protected HttpSession session;


	/**
	 * 根据类型查询配置信息列表
	 *
	 * @return
	 */
	@RequestMapping("/infolist/{id}")
	@ResponseBody
	public Map<String, Object> infolist(@PathVariable int id) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			jsonMap.put("Rows", confService.queryByType(id, null, null));
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "根据类型查询配置信息列表", e);
		}
		return jsonMap;
	}

	/**
	 * 全局配置
	 *
	 * @return
	 */
	@RequestMapping("/init")
	public ModelAndView initWithTree() {
		ModelAndView mv = new ModelAndView("/platform/conf.jsp");
		return mv;
	}

	/**
	 * @param id
	 * @return
	 */
	@RequestMapping("/queryById")
	@ResponseBody
	public Map<String, Object> queryById(Long id) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			jsonMap.put("dataList", confService.find(id));
			jsonMap.put("statusCode", 200);
		} catch(Exception e) {
			jsonMap.put("statusCode", 500);
			BaseLog.e(this.getClass(), "查询配置异常", e);
		}
		return jsonMap;
	}

	/**
	 * 图片上传
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/upload")
	@ResponseBody
	public void upload(DefaultMultipartHttpServletRequest request, HttpServletResponse response) {
		response.setContentType("text/html");
		try {
			Map<String, Object> jsonMap = new HashMap<String, Object>();
			String uri = SpringUploadFile.upload(request, "confPic").get("newUrl");
			if(uri != null && uri.length() > 0) {
				jsonMap.put("statusCode", 200);
				jsonMap.put("uri", uri);
			} else {
				jsonMap.put("statusCode", 500);
				jsonMap.put("info", "图片上传失败！");
			}
			response.getWriter().print(JsonUtil.toJson(jsonMap));
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "图片上传失败！", e);
		}
	}

	/**
	 * 更新（保存）配置项
	 *
	 * @param bo
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public Map<String, Object> save(ConfValue bo) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			if(bo.getId() != null && bo.getId() > 0) confService.update(bo);
			else {
				if("0".equals(bo.getPid()) || StringUtil.isNullOrEmpty(bo.getPid())){
					bo.setLevels(0);
				}else{
					ConfValue pbo = confService.findOne("id", bo.getPid());
					if(null!=pbo){
						int levels =0;
						levels = pbo.getLevels()==null?0:pbo.getLevels();
						bo.setLevels(levels+1);
					}
				}
				if(bo.getPid() == null) bo.setPid(0l);
				confService.save(bo);
			}
			jsonMap.put("data", bo.getId());
			jsonMap.put("statusCode", 200);
		} catch(Exception e) {
			jsonMap.put("statusCode", 500);
			BaseLog.e(getClass(), "配置保存异常！", e);
		}
		return jsonMap;
	}

	/**
	 * 删除 配置节点，如果该节点是父节点，会一并其子节点
	 *
	 * @param ids
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public Map<String, Object> delete(@RequestParam(value = "ids[]", defaultValue = "") Long[] ids) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			if(ids != null) {
			  // 删除 配置节点，如果该节点是父节点，会一并其子节点
				for(Long id : ids){
				  confService.delete(id);
				}
				jsonMap.put("statusCode", 200);
			}else {
				jsonMap.put("msg", "获取配置项失败！");
				jsonMap.put("statusCode", 500);
			}
		} catch(Exception e) {
			jsonMap.put("statusCode", 500);
			BaseLog.e(getClass(), "配置保存异常！", e);
		}
		return jsonMap;
	}

	@RequestMapping("/queryConfValue/{typeid}")
	@ResponseBody
	public Map<String, Object> queryConfValue(@PathVariable int typeid) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			jsonMap.put("dataList", confService.queryByType(typeid, null,null));
			jsonMap.put("statusCode", 200);
		} catch(Exception e) {
			jsonMap.put("statusCode", 500);
			BaseLog.e(this.getClass(), "查询配置异常", e);
		}
		return jsonMap;
	}

	/******************************************配置类型**********************************************/

	/**
	 * 获取配置类型列表
	 *
	 * @return
	 */
	@RequestMapping("/typelist")
	@ResponseBody
	public Map<String, Object> typelist() {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			
			// luzhirui 2015-09-17临时改造，只有系统管理员才能看到系统配置项
			// List<ConfType> list = confTypeService.findAll();
			List<ConfType> list = null;
			User user = (User)session.getAttribute("user");
			if ("superadmin".equals(user.getUsername())) {
				list = confTypeService.findAll();
			} else {
				list = confTypeService.find("level" ,1); // 只查询业务级配置项
			}
			// end ===============
			jsonMap.put("Rows", list);
			jsonMap.put("Total", list.size());
			jsonMap.put("msg", "success");
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "获取配置类型列表", e);
		}
		return jsonMap;
	}


	/**
	 * 更新（保存）配置项
	 *
	 * @param bo
	 * @return
	 */
	@RequestMapping("/saveType")
	@ResponseBody
	public Map<String, Object> saveType(ConfType bo) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {

			if(bo.getId() != null && bo.getId() > 0) confTypeService.update(bo);
			else confTypeService.save(bo);

			jsonMap.put("id", bo.getId());

			jsonMap.put("statusCode", 200);

		} catch(Exception e) {
			jsonMap.put("statusCode", 500);
			BaseLog.e(getClass(), "配置保存异常！", e);
		}
		return jsonMap;
	}

	/**
	 * 删除配置项
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping("/deleteType")
	@ResponseBody
	public Map<String, Object> deleteType(int id) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
		  confTypeService.deleteType(id);
			jsonMap.put("statusCode", 200);
		} catch(Exception e) {
			jsonMap.put("statusCode", 500);
			BaseLog.e(getClass(), "配置删除异常！", e);
		}
		return jsonMap;
	}

	/**
	 * @param id
	 * @return
	 */
	@RequestMapping("/queryTypeById")
	@ResponseBody
	public Map<String, Object> queryConfTById(int id) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			jsonMap.put("dataList", confTypeService.find(id));
			jsonMap.put("statusCode", 200);
		} catch(Exception e) {
			jsonMap.put("statusCode", 500);
			BaseLog.e(this.getClass(), "查询配置异常", e);
		}
		return jsonMap;
	}

	/**
	 * @param pid
	 * @return
	 */
	@RequestMapping("/queryConfTByPid")
	@ResponseBody
	public Map<String, Object> queryConfTByPid(Long pid) {
		Map<String, Object> jsonMap = new HashMap<>();
		try {
			jsonMap.put("dataList", confService.findConfValueByPid(pid));
			jsonMap.put("statusCode", 200);
		} catch(Exception e) {
			jsonMap.put("statusCode", 500);
			BaseLog.e(this.getClass(), "查询配置异常", e);
		}
		return jsonMap;
	}
}
